#!/bin/bash
set -xeuo pipefail
BASE_DIR=$(cd "$(dirname "$0")"; pwd)
cd ${BASE_DIR}

docker images |grep cypress-allinone ||(
 echo "没有Cyrpess定制的镜像文件"
 exit 1
)

# 换成cypree6.1.0 PUPPETEER_SKIP_CHROMIUM_DOWNLOAD 此类问题，不兼容
# https://github.com/cypress-io/cypress-realworld-app 还是使用下载时的6.0.1
# grep -rins '"cypress":' package.json |grep "6.1.0" ||(
#  echo "项目使用的cypress版本和镜像不一致"
#  exit 2
# )

PRJ=`basename $(pwd)`
if [ $(docker ps -a | grep ${PRJ}|wc -l) -eq "1" ]; then
 echo "start ${PRJ}"
 docker start ${PRJ}
else
 echo "run ${PRJ}"
 docker run -itd --name ${PRJ} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY -v $PWD:/e2e --network host -w /e2e --entrypoint=cypress dev.docker:8085/cypress-allinone:6.1.0 open --project .
 
 sleep 5
 docker ps | grep ${PRJ}
fi

#如果需要更换npm源，打开下面这个
docker exec -it ${PRJ} bash -c "npm config set registry https://registry.npm.taobao.org/; yarn config set registry https://registry.npm.taobao.org/"

:<<EOF
修正nodejs依赖引起的站点无法运行的情况
https://cdn.npm.taobao.org/dist/cypress/ 是cypress版本的下载
https://cdn.npm.taobao.org/dist/cypress/6.0.1/linux64/cypress.zip
EOF
if [ ! -f cypress.zip ]; then
 curl -o cypress.zip https://cdn.npm.taobao.org/dist/cypress/6.0.1/linux64/cypress.zip 
fi
docker exec -it ${PRJ} bash -c "[ -d /root/.cache/Cypress/6.0.1 ] || ( mkdir -p /root/.cache/Cypress/6.0.1; unzip /e2e/cypress.zip -d /root/.cache/Cypress/6.0.1 )"

echo "安装必要的一些nodejs包"
echo "依赖包安装成功后，就可运行了^_^"
docker exec -it ${PRJ} bash -c "[ -d node_modules ] || yarn install --verbose"

#启动vscode环境 Enjoy code life!!!
docker exec -it ${PRJ} bash -c vscode

echo "启动被测试的网站应用...[ http://localhost:3000 必须正常才可以测 ]"
docker exec -it ${PRJ} bash -c "cd /e2e/; yarn dev"
:<<EOF
使用6.1.0
Cypress 6.1.0 ./src/svgs/rwa-logo.svg (./node_modules/@svgr/webpack/lib?-svgo,+titleProp,+ref!./src/svgs/rwa-logo.svg)
TypeError: [BABEL] unknown: Cannot read property 'chrome' of undefined (While processing: "programmatic item")

不修改，直接使用原始的6.0.1 会出现下载cypress失败的情况,具体修改看上面的脚本，使用国内的镜像手动设置cypress6.0.1
yarn.lock这个很关键，删除后重建的话，由于版本的问题，网站也会出问题
EOF

echo "done"
